package cn.dao.impl;

import cn.dao.AccountDao;
import cn.pojo.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AccountDaoImpl implements AccountDao {
    @Autowired
    private QueryRunner runner;

    /**
     * 增删改全用QueryRunner的update方法
     * xml中的 jdbtTemplate类似，也是增删改全用update
     */
    public void addAccount(Account account) {
        try {
            String sql = " insert into t_account(name,money) values (?,?) ";
            runner.update(sql, account.getName(), account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public void deleteAccount(Integer id) {
        try {
            String sql = " delete from t_account where id=? ";
            runner.update(sql, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            String sql = " update t_account set name=? , money=? where id=? ";
            runner.update(sql, account.getName(), account.getMoney(), account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer id) {
        try {
            String sql = " select * from t_account where id=? ";
            // 类似于JdbcTemplate中的RowMapper
            BeanHandler<Account> beanHandler = new BeanHandler<Account>(Account.class);
            return runner.query(sql, beanHandler, id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<Account> findAll() {
        try {
            String sql = " select * from t_account ";
            BeanListHandler<Account> beanListHandler = new BeanListHandler<Account>(Account.class);
            return runner.query(sql, beanListHandler);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
